<template>
  <div id="channel-detail" class="detailDialog">
    <el-card>
      <div class="panel">
        <div v-if="$api.buttonPower(57)" style="text-align: right">
          <el-button type="primary" @click="setOpen">编辑</el-button>
          <el-button v-if="detail.status == 1" type="success" @click="changeStatus(2, '激活')">激活</el-button>
          <el-button v-if="detail.status == 2" type="danger" @click="changeStatus(1, '停用')">停用</el-button>
        </div>

      </div>

      <el-descriptions :column="2" :colon="false" label-class-name="dialogLabel">
        <el-descriptions-item label="编码">{{ detail.coding }}</el-descriptions-item>
        <el-descriptions-item label="名称">{{ detail.title }}</el-descriptions-item>
        <el-descriptions-item label="驱动">{{detail.driver_name}}</el-descriptions-item>
        <el-descriptions-item label="状态">
            <el-tag :type="detail.status === 1 ? 'danger' : 'success'">{{ detail.status_name}}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="运营商">{{ detail.operator_key_name }}</el-descriptions-item>
        <el-descriptions-item label="类型">{{ detail.type_name }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detail.create_dt }}</el-descriptions-item>
      </el-descriptions>

      <div v-for="(item, index) in option[$api.Enum.DicTypeChannelDrive]" :key="index">
        <div v-if="item.key == detail.driver">
          <el-descriptions :column="2" :colon="false" label-class-name="dialogLabel" style="margin-top: 20px">
            <el-descriptions-item v-for="(item, index) in item.extend.fields" :key="index" :label="item.name">
              {{ detail.options[item.key] }}
            </el-descriptions-item>
            <el-descriptions-item label="最大白名单数量">{{ detail.options.max_whitelist_number }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-card>

    <el-card v-if="speed_box.limits !== null">
      <div slot="header" class="clearfix">
        <span>限速规则</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="speedOpen(null)">新增规则</el-button>
      </div>
      <div>
        <el-table :data="speed_list.list" max-height="420" :fit="true"> <!-- v-fit-columns  -->
          <el-table-column label="名称" prop="title"></el-table-column>
          <el-table-column label="模式" prop="mode_name" width="70"></el-table-column>
          <el-table-column label="规则" align="left" style="white-space: normal;">
            <template slot-scope="{row}">
              <el-tag v-for="item in row.rules" type="info" effect="plain" style="margin-right: 4px;display: block;text-align: left;padding-left: 1px;">
                <i class="el-icon-arrow-right"></i>{{item.max_value}} {{item.mode== 1 ? '%' : 'MB'}} &nbsp; [{{item.speed}}]
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="应用套餐组" style="white-space: normal;">
            <template slot-scope="{row}">
              <el-tag v-for="item in row.combo_group_names" type="info" effect="plain" style="margin-right: 4px;display: block;text-align: left">
                {{item}}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="100">
            <template slot-scope="{row}">
              <el-button @click="speedOpen(row)" type="text" size="small">编辑</el-button>
              <el-button @click="speedRangeDel(row)" type="text" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!--速率设置-->
      <el-dialog title="设置限速规则" :visible.sync="speed_box.show" width="456px" append-to-body>
        <el-form :model="speed_box.form" label-position="left">
          <el-form-item label="规则名称" label-width="75px">
            <el-input v-model="speed_box.form.title"></el-input>
          </el-form-item>
          <el-form-item>
            当用量<el-select v-model="speed_box.form.mode" placeholder="请选择模式" class="speed-mode" :clearable="false">
            <el-option v-for="item in option[this.$api.Enum.TypeSpeedLimitMode]" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-for="(item, index) in speed_box.form.rules" class="speed-limit">
            大于<i class="el-icon-arrow-right"></i><el-input v-model="item.max_value" @input="speedRangeAdd"></el-input>
             {{speed_box.form.mode == 1 ? '%' : 'MB'}} 时，限速
            <el-select v-model="item.speed" placeholder="请选择速率">
              <el-option v-for="(item,index) in speed_box.limits" :label="item.name" :value="item.name"></el-option>
            </el-select>
            <button style="float: right;margin-top: 7px;">
              <i class="el-icon-close"></i>
            </button>
          </el-form-item>
          <el-form-item label="应用套餐组" label-width="85px">
            <el-select v-model="speed_box.form.combo_group_ids" multiple >
              <el-option v-for="item in option[this.$api.Enum.DicTypeComboGroupList]" :label="item.name" :value="item.id" :disabled="speed_box.combo_group_selected.includes(item.id)"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item style="margin-top: 18px">
            <el-button @click="speedSubmit">确定</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </el-card>


    <!-- 编辑 -->
    <el-dialog title="编辑渠道" :visible.sync="is_set" width="50%" :wrapperClosable="false" append-to-body>
      <iot-channel-set v-if="is_set" :detail="detail" @close="setClose"></iot-channel-set>
    </el-dialog>
  </div>
</template>

<script>
import IotChannelSet from "@/components/iotCard/channel/channelSet";
export default {
  name: "IotChannelDetail",
  components: {IotChannelSet},
  props:{
    data_id: Number,
  },
  data(){
    return {
      option:{},
      detail:{},
      is_set: false,
      is_change: false,

      speed_list:{
        list:[],
        page:{},
      },
      speed_box:{
        show:false,
        form:{},
        limits: null, // null 表示没有支持限速
        combo_group_selected: [] // 已选中的套餐组
      }
    }
  },
  watch:{
    data_id:{
      immediate: true, // 解决首次负值不触发的情况
      handler: function (newVal,oldVal){
        if (newVal){
          // this.getDetail()
        }
      },
    }
  },
  mounted() {
    this.$api.foundation.dicListExtendCache(
        [
          this.$api.Enum.DicTypeChannelDrive,
          this.$api.Enum.TypeSpeedLimitMode,
          this.$api.Enum.DicTypeComboGroupList,
        ],
        {},
        res => {
          this.option = res;
          this.getDetail() // 这里有依赖关系
        }
    );

    this.getSpeedList()
  },
  // 销毁之前
  beforeDestroy() {
    if (this.is_change){
      this.$emit('close')
    }
  },
  methods:{
    getDetail(){
      this.$api.channel.detail({id: this.data_id}, res => {
        if (!res.status) {
          return this.$message.error(res.message);
        }
        this.detail = res.data;
        if (this.speed_box.limits == null){
          this.option[this.$api.Enum.DicTypeChannelDrive].forEach((item)=>{
            if (item.key == this.detail.driver){
              this.speed_box.limits = item.extend.speed_limit??null
              return
            }
          })
        }
      });
    },
    setOpen() {
      this.is_set = true
      this.is_change = true
    },
    setClose(){
      this.is_set = false
      this.getDetail()
    },
    // 修改状态
    changeStatus(new_status, title) {
      this.$confirm("你确定" + title + this.detail.title + "吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      }).then(() => {
        this.$api.channel.changeStatus({ id: this.detail.id, status: new_status }, res => {
          if (!res.status) {
            return this.$message.error(res.message);
          }
          this.$message.success("状态修改成功!");
          this.getDetail();
          this.is_change = true
        });
      });
    },
    // 速率 列表
    getSpeedList(){
      this.$api.channel.speedList({channel_id: this.data_id}, res => {
        if (!res.status) {
          return this.$message.error(res.message);
        }
        this.speed_list = res.data;
      })
    },
    speedOpen(row){
      row = this.$tool.copyJSON(row)
      this.speed_box.show = true
      if (!row){
        row = {id:0, title:'', mode: 2, rules:[{max_value:'',speed:''}], combo_group_ids:[]}
      }else {
        row.rules.push({max_value:'',speed:''})
      }
      // 获取已选中套餐组集合
      this.speed_box.combo_group_selected = []
      this.speed_list.list.forEach((item)=>{
        if (item.id !== row.id){
          this.speed_box.combo_group_selected.push(...item.combo_group_ids)
        }
      })
      console.log("speedOpen",this.speed_box)

      this.speed_box.form = row
    },
    // 输入值变化时
    speedRangeAdd(val){
      if (val == ""){
        return
      }
      let item = this.speed_box.form.rules.slice(-1)[0]
      if (item === undefined || item.max_value !== ""){
        this.speed_box.form.rules.push({max_value:'',speed:''})
      }
    },
    speedRangeDel(row){
      this.$confirm('确定删除限速规则吗？', '提示',{type: 'warning'}).then(()=>{
        this.$api.channel.speedChangeStatus({id:row.id, status:this.$api.Enum.StatusDelete}, res => {
          if (!res.status) {
            return this.$message.error(res.message);
          }
          this.$message.success("操作成功!");
          this.getSpeedList()
        })
      })
    },
    // 速率 设置 表单提交
    speedSubmit(){
      let body = this.$tool.copyJSON(this.speed_box.form)
      if (!body.title){
        return this.$message.warning("请输入名称")
      }
      body.mode = Number(body.mode)
      if (body.mode === 0){
        return this.$message.warning("请选择模式")
      }
      body.channel_id = this.data_id
      let last_max_value = -1 // 上一次的最大值，必须比下一次小
      body.rules = body.rules.filter((item)=> {
        if (item.max_value === ''){
          return false;
        }
        item.max_value = Number(item.max_value)
        if (last_max_value > -2){
          if ( last_max_value >= item.max_value){
            last_max_value = -2
            this.$message.warning("提交失败，边界值 "+item.max_value+" 必须大于上一次边界值")
          }else {
            last_max_value = item.max_value
          }
        }
        return true;
      })
      if (last_max_value == -2){
        return
      }

      this.$api.channel.speedSet(body, res => {
        if (!res.status) {
          return this.$message.error(res.message);
        }
        this.$message.success("操作成功!");
        this.getSpeedList()
        this.speed_box.show =false
      })
    }
  }
}
</script>

<style lang="less" scoped>
.detailDialog {
  padding: 0 20px;

  .panel {
    margin-bottom: 20px;
  }
}
.speed-mode{
  display: inline-block;
  width: 120px;
  margin: 0 5px;
}

.speed-limit{
  margin-bottom: 5px;
  .el-form-item__content>div{
    display: inline-block;
    width: 120px;
  }
}
</style>